package com.demo.mystudy.ui.socketserver

import android.util.Log
import com.demo.mystudy.socketbean.MessageWrapper
import com.demo.mystudy.ui.socketserver.servercmd.ServerCmdDownloadFile
import com.demo.mystudy.ui.socketserver.servercmd.ServerCmdInterface
import com.demo.mystudy.ui.socketserver.servercmd.ServerCmdJetinnoFolder
import com.jetinno.simple.utils.JsonUtil
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress

/**
 * Created by zhangyuncai on 2025/4/27.
 * 描述：
 */
class MyWebSocketServer(port: Int) : WebSocketServer(InetSocketAddress(port)) {
    init {
        // 设置SO_REUSEADDR选项
        setReuseAddr(true);
    }

    override fun onStart() {
        Log.d("WebSocketServer", "服务器启动成功，等待连接...")
        WebSocketServerManager.isOpened = true
        WebSocketServerManager.callback?.onSocketStatusChanged(true)
        addData("服务器启动成功，等待连接...")
    }

    override fun onOpen(conn: WebSocket, handshake: ClientHandshake) {
        Log.d("WebSocketServer", "有设备连接: ${conn.remoteSocketAddress}")
//        conn.send("欢迎连接到服务器！")
        addData("有设备连接: ${conn.remoteSocketAddress}")
    }

    override fun onClose(conn: WebSocket, code: Int, reason: String, remote: Boolean) {
        Log.d("WebSocketServer", "连接关闭: ${conn.remoteSocketAddress}，原因: $reason")
        addData("连接关闭: ${conn.remoteSocketAddress}，原因: $reason")
    }

    override fun onMessage(conn: WebSocket, message: String) {
        Log.d("WebSocketServer", "收到消息: $message")
//        conn.send("服务器已收到: $message") // 回个消息
        val messageWrapper =
            JsonUtil.jsonToAny<MessageWrapper>(message, MessageWrapper::class.java)!!
        messageWrapper.message = message
        addData("服务器已收到: $message")
        WebSocketServerManager.receiveMessage(conn, messageWrapper)
    }

    override fun onError(conn: WebSocket?, ex: Exception) {
        Log.e("WebSocketServer", "发生错误: ${ex.message}")
        addData("发生错误: ${ex.message}")
    }

    override fun stop() {
        super.stop()
        WebSocketServerManager.isOpened = false
        WebSocketServerManager.callback?.onSocketStatusChanged(false)
        addData("服务器已关闭")
    }


    private fun addData(msg: String) {
        WebSocketServerManager.addData(msg)
    }
}

object WebSocketServerManager {
    val mDatas = arrayListOf<String>()
    var server: MyWebSocketServer? = null
    var isOpened = false
    var callback: SocketServerCallback? = null
    private val cmdMap: HashMap<String, ServerCmdInterface> by lazy {
        val list = mutableListOf<ServerCmdInterface>()
        list.add(ServerCmdJetinnoFolder)
        list.add(ServerCmdDownloadFile)
        val map = hashMapOf<String, ServerCmdInterface>()
        for (cmdInterface in list) {
            map[cmdInterface.cmd] = cmdInterface
        }
        map
    }

    fun openSocket() {
        server?.stop()
        server = MyWebSocketServer(9527)
        server!!.start()
    }

    fun closeSocket() {
        server?.stop()
        server = null
    }

    internal  fun addData(msg: String) {
        if (mDatas.size >= 10) {
            mDatas.removeAt(0)
        }
        mDatas.add(msg)
        callback?.addData(msg)
    }

    internal fun receiveMessage(conn: WebSocket, messageWrapper: MessageWrapper) {
        val cmd = messageWrapper.cmd
        if (cmdMap.containsKey(cmd)) {
            val cmdInterface = cmdMap.get(cmd)!!
            cmdInterface.receive(conn,messageWrapper)
        }
    }

}

interface SocketServerCallback {
    fun addData(msg: String)
    fun onSocketStatusChanged(isOpened: Boolean)
}